<?php
/**
 * Ecart
 *
 * This file is part of Ecart.
 *
 * Ecart is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Ecart is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Ecart.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @category    Ecart
 * @package     Ecart_Admin
 * @copyright   Copyright 2008-2009 E-Cart LLC
 * @license     GNU Public License V3.0
 */

/**
 *
 * @category    Ecart
 * @package     Ecart_Admin
 * @subpackage  Controller
 * @author      Ecart Core Team <core@ecartcommerce.com>
 */
class Ecart_Admin_Cms_IndexController extends Ecart_Admin_Controller_Back
{

    public function indexAction()
    {
        $this->view->pageTitle = Ecart::translate('cms')->__(
            'Categories/Pages'
        );

        $result = "";

        function getChilds($node, $root) {
            $result = "";
            $tableCmsCategory = Ecart::single('admin/cms_category');

            //if !$root -> load subcategories, else -> load root categories of site
            if ($root) {
                $cats = $tableCmsCategory->getRootCategory($node);
            } else {
                $cats = $tableCmsCategory->getChildCategory($node);
            }

            //get categories
            if (sizeof($cats)) {
                $result .= "menu: [";
                foreach ($cats as $cat) {
                    $result .= "{
                        text: '$cat[name]',
                        " . getChilds($cat['id'], false) . "
                        handler: function() {
                            batch('category', $cat[id]);
                        }
                    },\n";
                }
                $result = substr($result, 0, -2);
                $result .= "],";
                return $result;
            } else {
                return false;
            }
        }

        //autogenerated nodes
        foreach (Ecart_Collect_Site::collect() as $siteId => $siteName) {
            $result .= "{
                    " . getChilds($siteId, true). "
                    text: '$siteName'
            },\n";
        }

        $this->view->categoryMenu = substr($result, 0, -2);

        $this->render();
    }

    public function getSiteTreeAction()
    {
        $this->_helper->layout->disableLayout();

        $result = array();

        function getChilds($node, $root) {
            $result = array();
            $tableCmsCategory = Ecart::single('admin/cms_category');

            //if !$root -> load subcategories, else -> load root categories of site
            if ($root) {
                $cats = $tableCmsCategory->getRootCategory($node);
            } else {
                $cats = $tableCmsCategory->getChildCategory($node);
            }

            //get categories
            foreach ($cats as $cat) {
                $result[] = array(
                    'leaf' => false,
                    'id' => $cat['id'],
                    'siteId' => 'null',
                    'text' => $cat['name'],
                    'iconCls' => 'icon-folder',
                    'expanded' => true,
                    'cls' => $cat['is_active'] ? '' : 'disabledNode',
                    'children' => getChilds($cat['id'], false)
                );
            }
            return $result;
        }

        //autogenerated nodes
        foreach (Ecart_Collect_Site::collect() as $siteId => $siteName) {
            $result[] = array(
                    'leaf'     => false,
                    'id'       => "_" . $siteId,
                    'siteId'   => $siteId,
                    'text'     => $siteName,
                    'checked'  => 'undefined',
                    'iconCls'  => 'icon-folder',
                    'cls'      => 'root-node',
                    'expanded' => true,
                    'children' => getChilds($siteId, true)
            );
        }
        $this->_helper->json->sendJson($result, false, false);
    }

    public function saveCategoryAction()
    {
        $this->_helper->layout->disableLayout();
        $data = $this->_getAllParams();

        $modelCategoryContent = Ecart::single('cms/category_content');
        $modelCategory = Ecart::single('admin/cms_category');

        /* save category */
        $rowCategory = array(
            'name' => $data['name'],
            'is_active' => $data['is_active'] != '' ? $data['is_active'] : 1
        );

        if ($data['catId'] == 'new') {
            if ($data['parentId']) {
                $rowCategory['parent_id'] = $data['parentId'];
                $rowCategory['site_id']   = $modelCategory
                    ->find($data['parentId'])
                    ->current()
                    ->site_id;
            } else {
                $rowCategory['site_id']   = $data['siteId'];
            }
            //$rowCategory['parent_id'] = $data['parentId'] ? $data['parentId'] : new Zend_Db_Expr('NULL');
            //$rowCategory['site_id']   = $data['siteId'] ? $data['siteId'] : new Zend_Db_Expr('NULL');
            $catId = $modelCategory->insert($rowCategory);
        } else {
            $catId = $data['catId'];
            $currentCategory = $modelCategory->find($data['catId'])->current();
            $currentCategory->setFromArray($rowCategory);
            $currentCategory->save();
        }

        $rowKeyset = array('title', 'description', 'link',
            'meta_title', 'meta_keyword', 'meta_description'
        );
        /* save category content */
        foreach (array_keys(Ecart_Collect_Language::collect()) as $languagesId) {
            $rowContent = array();
            foreach ($rowKeyset as $key) {
                $rowContent[$key] = isset($data[$key . '_' . $languagesId]) ?
                    $data[$key . '_' . $languagesId] : new Zend_Db_Expr('NULL');
            }

            if ($row = $modelCategoryContent->find($catId, $languagesId)->current()) {
                $row->setFromArray($rowContent);
            } else {
                $row = $modelCategoryContent->createRow($rowContent);
                $row->cms_category_id = $catId;
                $row->language_id = $languagesId;
            }
            $row->save();
        }
        Ecart::message()->addSuccess(
            Ecart::translate('cms')->__(
                'Category was saved successfully'
        ));
        $this->_helper->json
            ->setData(array('catId' => $catId))
            ->sendSuccess();
    }

    public function moveCategoryAction()
    {
        $this->_helper->layout->disableLayout();

        $data = $this->_getAllParams();

        $tableCategory = Ecart::single('admin/cms_category');
        $success = true;
        if ($data['parentId']) {
            $success = $tableCategory->update(array(
                'parent_id' => $data['parentId'] ?
                        $data['parentId'] : new Zend_Db_Expr('NULL'),
                'site_id'   => $tableCategory->find($data['parentId'])
                        ->current()->site_id
            ), Ecart::db()->quoteInto('id = ' . $data['catId']));
        } else {
            $success = $tableCategory->update(array(
                'parent_id' => new Zend_Db_Expr('NULL'),
                'site_id'   => $data['siteId']
            ), Ecart::db()->quoteInto('id = ?',$data['catId']));
        }

        $this->_helper->json->sendJson(array(
            'success' => $success
        ));
    }

    public function getCategoryAction()
    {
        $this->_helper->layout->disableLayout();

        $categoryId = $this->_getParam('catId');

        $rowCategory = Ecart::single('admin/cms_category')
            ->find($categoryId)
            ->current();
        $content = Ecart::model('cms/category_content')
            ->select(array('language_id', '*'))
            ->where('ccc.cms_category_id = ?', $rowCategory->id)
            ->fetchAssoc();

        $category = array();

        $keyset = array(
            'title', 'link', 'description',
            'meta_title', 'meta_keyword', 'meta_description'
        );

        foreach(Ecart_Collect_Language::collect() as $languageId => $lName) {
            foreach ($keyset as $key) {
                $category[$key . '_' . $languageId] =
                    isset($content[$languageId][$key]) ?
                        $content[$languageId][$key] : new Zend_Db_Expr('NULL');
            }
        }

        $category['name']      = $rowCategory->name;
        $category['is_active'] = $rowCategory->is_active;

        $this->_helper->json
            ->setCategory(array($category))
            ->sendSuccess();
    }

    public function deleteCategoryAction()
    {
        $this->_helper->layout->disableLayout();

        $categoryId = $this->_getParam('id');

        $success = Ecart::single('admin/cms_category')->delete(
            Ecart::db()->quoteInto('id IN(?)', $categoryId)
        );
        if ($success) {
            Ecart::message()->addSuccess(
                Ecart::translate('cms')->__(
                    'Category was deleted successfully'
            ));
        }
        $this->_helper->json->sendJson(array(
            'success' => $success
        ));
    }

    public function getPagesAction()
    {
        $this->_helper->layout->disableLayout();

        $filterTree   = $this->_getParam('filterTree');
        $filterSearch = $this->_getParam('filterSearch');

        $start = (int) $this->_getParam('start', 1);
        $limit = (int) $this->_getParam('limit', false);

        $sort  = $this->_getParam('sort', false);
        $dir   = $this->_getParam('dir', 'ASC');

        $select = Ecart::model('admin/cms_page')
            ->select('*')
            ->calcFoundRows()
            ->addContent($this->_langId)
            ->group('cp.id')
            ->addCategoryName()
            ;
        switch ($filterTree['type']) {
            case 'site':
                $select->addSiteFilter($filterTree['data']);
                break;
            case 'category':
                $select->addCategoriesFilter($filterTree['data']);
                break;
        }

        if (!empty($filterSearch['query'])) {
            $select->where("cp.name LIKE ?", "%" . $filterSearch['query'] . "%");
        }

        if (false === $sort) {
            $select->order($sort . ' ' . $dir);
        }
        if (false === $limit) {
            $select->limit($limit, $start);
        }

        $this->_helper->json
            ->setPages($select->fetchAll())
            ->setTotalCount($select->count())
            ->sendSuccess();
    }

    public function getPageDataAction()
    {
        $this->_helper->layout->disableLayout();

        $pageId = $this->_getParam('pageId');

        $rowPage = Ecart::single('admin/cms_page')
            ->find($pageId)
            ->current();
        $content = Ecart::model('cms/page_content')
            ->select(array('language_id', '*'))
            ->where('cpc.cms_page_id = ?', $rowPage->id)
            ->fetchAssoc();

        $category = Ecart::model('cms/page_category')
            ->select('cms_category_id')
            ->where('cpc.cms_page_id = ?', $rowPage->id)
            ->fetchCol()
            ;

        $page = array(
            'is_active' => $rowPage->is_active,
            'layout'    => $rowPage->layout,
            'comment'   => $rowPage->comment,
            'access'    => $rowPage->access,
            'name'      => $rowPage->name
        );

        $keyset = array(
            'title', 'link', 'content',
            'meta_keyword','meta_title', 'meta_description'
        );

        foreach(Ecart_Collect_Language::collect() as $languageId => $lName) {
            foreach ($keyset as $key) {
                $page[$key . '_' . $languageId] =
                    isset($content[$languageId][$key]) ?
                        $content[$languageId][$key] : '';
            }
        }

        $this->_helper->json
            ->setPage(array($page))
            ->setCategory($category)
            ->sendSuccess();

    }

    public function savePageAction()
    {
        $this->_helper->layout->disableLayout();

        $data = $this->_getAllParams();
        $modelPage = Ecart::single('admin/cms_page');
        $modelPageContent = Ecart::single('cms/page_content');

        /* save page */
        $rowPage = array(
            'is_active' => (int) $data['is_active'],
            'layout'    => $data['layout'],
            'comment'   => (int) $data['comment'],
            'name'      => $data['name']
        );
        if ($data['pageId'] == 'new') {
            $pageId = $modelPage->insert($rowPage);
        } else {
            $pageId = $data['pageId'];
            $currentPage = $modelPage->find($pageId)->current();
            $currentPage->setFromArray($rowPage);
            $currentPage->save();
        }

        /*
         * Save page_to_category links
         */
        $modelCategory = Ecart::single('cms/page_category');
        $modelCategory->delete(
            Ecart::db()->quoteInto('cms_page_id = ?', $pageId)
        );

        foreach (Zend_Json::decode($data['category']) as $categoryId) {
            if (false !== strpos($categoryId, '_')) {
                continue;
            }

            $modelCategory->insert(array(
                'cms_category_id' => $categoryId,
                'cms_page_id'     => $pageId
            ));
        }


        $keyset = array(
            'title', 'link', 'description', 'content',
            'meta_title', 'meta_keyword', 'meta_description'
        );

        foreach (Ecart_Collect_Language::collect() as $languageId => $lName) {
            $rowContent = array();
            foreach ($keyset as $key) {
                $rowContent[$key] =
                    isset($data[$key . '_' . $languageId]) ?
                        $data[$key . '_' . $languageId] : new Zend_Db_Expr('NULL');
            }
            if ($row = $modelPageContent->find($pageId, $languageId)->current()) {
                $row->setFromArray($rowContent);
            } else {
                $row = $modelPageContent->createRow($rowContent);
                $row->cms_page_id = $pageId;
                $row->language_id = $languageId;
            }
            $row->save();
        }
        if ('new' == $data['pageId']) {
            Ecart::dispatch('cms_page_add_success', array(
                'page_id' => $pageId
            ));
        } else {
            Ecart::dispatch('cms_page_update_success', array(
                'page_id' => $pageId
            ));
        }
        Ecart::message()->addSuccess(
            Ecart::translate('cms')->__(
                'Page was saved successfully'
        ));
        $this->_helper->json->sendSuccess();

    }

    public function quickSavePageAction()
    {
        $this->_helper->layout->disableLayout();

        $pages = Zend_Json_Decoder::decode($this->_getParam('data'));

        $modelPage = Ecart::single('admin/cms_page');
        $modelPageContent = Ecart::single('cms/page_content');

        foreach ($pages as $pageId => $values) {
            $modelPage->update(array(
                'name'        => $values['name'],
                'is_active'   => (int) $values['is_active'],
                'comment'     => (int) $values['comment'],
                'layout'      => $values['layout'],
                'show_in_box' => $values['show_in_box']
            ), Ecart::db()->quoteInto('id = ?', $pageId));

            if (!$row = $modelPageContent->find($pageId, $this->_langId)->current()) {
                $row = $modelPageContent->createRow(array(
                    'cms_page_id' => $pageId,
                    'language_id' => $this->_langId
                ));
            }
            $row->link = '' == $values['link'] ?
                new Zend_Db_Expr('NULL') : $values['link'];
            $row->save();
        }
        Ecart::message()->addSuccess(
            Ecart::translate('cms')->__(
                'Page was saved successfully'
        ));
        $this->_helper->json->sendSuccess();
    }

    public function deletePageAction()
    {
        $this->_helper->layout->disableLayout();

        $data = Zend_Json::decode($this->_getParam('data'));
        //$catId = $this->_getParam('catId');
        $params = $this->_getAllParams();

        if ($params['catId'] == 'all' || $params['catId'] == 'lost') {

            $where = Ecart::db()->quoteInto('id IN (?)', $data);
            Ecart::single('admin/cms_page')->delete($where);

        } else if ($params['siteId'] != 'null') {

            $where = Ecart::db()->quoteInto('cms_page_id IN (?)', $data);

            Ecart::single('cms/page_category')
                ->deleteBySiteId($where, $params['siteId']);
        } else {
            $where = Ecart::db()->quoteInto(
                'cms_category_id = ?', $params['catId']
            );
            $where .= Ecart::db()->quoteInto('AND cms_page_id IN (?)', $data);

            Ecart::single('cms/page_category')->delete($where);
        }
        Ecart::message()->addSuccess(
            Ecart::translate('cms')->__(
                'Page was deleted successfully'
        ));
        $this->_helper->json->sendSuccess();
    }

    public function copyPageAction()
    {
        $this->_helper->layout->disableLayout();

        $pages = Zend_Json::decode($this->_getParam('pages'));
        $categoryId = $this->_getParam('catId');


        foreach ($pages as $page) {
            Ecart::single('cms/page_category')->delete(
                "cms_page_id = '$page' AND cms_category_id = '$categoryId'"
            );
        }

        foreach ($pages as $page) {
            Ecart::single('cms/page_category')->insert(array(
                'cms_page_id'     => $page,
                'cms_category_id' => $categoryId
            ));
        }

        $this->_helper->json->sendSuccess();
    }
}